//
//  DispatchViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 02-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "DispatchViewController_iPad.h"
#import "dao.h"

@interface DispatchViewController_iPad ()

@end

@implementation DispatchViewController_iPad

@synthesize lblNombreCompleto, lblDireccion, lblCelular, lblCiudad, lblComuna, lblReferencia, lblFormaPago;

@synthesize json;
@synthesize btnNext, btnEdit, objActivityClientInfo, viewSavingClientInfo;

- (NSString *) obtenerRutaBD{
    NSString *dirDocs;
    NSArray *rutas;
    NSString *rutaBD;
    
    rutas = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    dirDocs = [rutas objectAtIndex:0];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    rutaBD = [[NSString alloc] initWithString:[dirDocs stringByAppendingPathComponent:@"ecommerce.sqlite"]];
    
    if([fileMgr fileExistsAtPath:rutaBD] == NO){
        [fileMgr copyItemAtPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ecommerce.sqlite"] toPath:rutaBD error:NULL];
    }
    
    return rutaBD;
}

- (void) retrieveClient{
    
    dao *objDAO = [[dao alloc] init];
    int intIdUser;
    
    intIdUser = [objDAO obtainCurrentIdUser];
    
    NSString *ubicacionDB = [self obtenerRutaBD];
    
    if(!(sqlite3_open([ubicacionDB UTF8String], &bd) == SQLITE_OK)){
        NSLog(@"Database connection failure irn");
    }
    
    NSString *sqlSelect = [NSString stringWithFormat:@"SELECT MC_RUT_CLIENTE, MC_DIGITO, MC_NOMBRE_COMPLETO, MC_APELLIDOS, MC_TELEFONO, MC_DIA, MC_MES, MC_ANO, MC_SEXO, MCLI_FORMA_PAGO FROM ECOM_MAESTRO_CLIENTES WHERE USIS_ID = %i", intIdUser];
    
    const char *sentenciaSQL = [sqlSelect UTF8String];
    
    sqlite3_stmt *sqlStatement;
    
    if(sqlite3_prepare_v2(bd, sentenciaSQL, -1, &sqlStatement, NULL) != SQLITE_OK){
        NSLog(@"Exception to prepare statement");
    }
    
    NSString *strRutCliente, *strIdComuna, *strDigito, *strNombreCompleto, *strApellidos, *strTelefono, *strDia, *strMes, *strAno, *strSexo, *strFormaPago;
    
    while(sqlite3_step(sqlStatement) == SQLITE_ROW){
        
        strRutCliente = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
        
        strDigito = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
        
        strNombreCompleto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
        
        strApellidos = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
        
        strTelefono = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
        
        strDia = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
        
        strMes = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
        
        strAno = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,7 )];
        
        strSexo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,8 )];
        
        strFormaPago = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,9 )];
    }
    
    NSLog(@"strRutCliente     =%@", strRutCliente);
    NSLog(@"strIdComuna       =%@", strIdComuna);
    NSLog(@"strDigito         =%@", strDigito);
    
    NSLog(@"strNombreCompleto =%@", strNombreCompleto);
    NSLog(@"strApellidos      =%@", strApellidos);
    NSLog(@"strTelefono       =%@", strTelefono);
    
    NSLog(@"strDia =%@", strDia);
    NSLog(@"strMes =%@", strMes);
    NSLog(@"strAno =%@", strAno);
    
    NSLog(@"strSexo=%@", strSexo);
    NSLog(@"strFormaPago=%@", strFormaPago);
    
    lblNombreCompleto.text = [NSString stringWithFormat:@"%@ %@", strNombreCompleto, strApellidos];
    
    lblCelular.text = strTelefono;
    
    [self retrieveClientDirection];
/*
    viewSavingClientInfo.hidden = YES;
    
    btnNext.hidden = NO;
    btnEdit.hidden = NO;
*/
}

-(void) retrieveClientDirection{
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = 0;
    NSArray *ArrayDireccion;
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    ArrayDireccion = [objDAO obtainDireccionCliente:intIdUsuario];
    
    /*
     strRut                 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
     strDireccion           = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
     strNumero              = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
     strReferencia          = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
     strIdUsuario           = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
     strIdComuna            = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
     strDescripcionComuna   = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
     */
    
    if (ArrayDireccion.count > 0) {
        
        lblDireccion.text = [NSString stringWithFormat:@"%@ %@", ArrayDireccion[1], ArrayDireccion[2]];
        
        //make mutable string
        NSMutableString *stringToTrim = [ArrayDireccion[6] mutableCopy];
        
        //pass it by reference to CFStringTrimSpace
        CFStringTrimWhitespace((__bridge CFMutableStringRef) stringToTrim);
        
        lblComuna.text = [NSString stringWithFormat:@"%@, Santiago", stringToTrim];
        
        lblCiudad.text = @",Santiago";
        lblReferencia.text = ArrayDireccion[3];
    }
    
}

/*
- (bool) clientDirectionInfoCloud:(int) intIdUsuario intRutCliente:(int) intRutCliente{
    
    dao *objDAO = [[dao alloc] init];
    
    int intRetorno = 0;
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com//MobileJsonCliente.aspx?strJsonBase=JsonDireccionCliente&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        //[{"iddir":"46", "tdir":"1", "idcom":"3", "idcom":"Lampa", "idciu":"4", "idciu":"Santiago", "dir":"Centenario de San Miguel", "numd":"935", "desc":"", "ref":"Costado lider", "nom":"", "ape":"", "ctel":"", "tel":"" }]
        
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        [objDAO deleteDireccionCliente:intIdUsuario];
        
        int intIdDireccionClienteiPad = [ [[json objectAtIndex:0] objectForKey:@"iddir"] intValue];
        
        int intIdComuna = 1; //[ [[json objectAtIndex:0] objectForKey:@"idcom"] intValue];
        
        NSString *strStreet = [[json objectAtIndex:0] objectForKey:@"dir"];
        
        NSString *strNumberStreet = [[json objectAtIndex:0] objectForKey:@"numd"];
        
        NSString *strReference = [[json objectAtIndex:0] objectForKey:@"ref"];
        
        
        intRetorno = [objDAO insertDireccionCliente:intIdUsuario intIdDireccion:intIdDireccionClienteiPad intRutCliente:intRutCliente strDireccion:strStreet strNumero:strNumberStreet strReferencia:strReference intIdComuna: intIdComuna];
        
        if (intRetorno <= 0) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"Error al actualizar la dirección del cliente, intente nuevamente."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return NO;
            
        }else{
            
            return YES;
        }
        
        
    }else{
        return NO;
    }
    
}
*/

- (bool) clientDirectionInfoCloud:(int) intIdUsuario intRutCliente:(int) intRutCliente{
    
    dao *objDAO = [[dao alloc] init];
    
    int intRetorno = 0;
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com//MobileJsonCliente.aspx?strJsonBase=JsonDireccionCliente&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        //[{"iddir":"46", "tdir":"1", "idcom":"3", "idcom":"Lampa", "idciu":"4", "idciu":"Santiago", "dir":"Centenario de San Miguel", "numd":"935", "desc":"", "ref":"Costado lider", "nom":"", "ape":"", "ctel":"", "tel":"" }]
        
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        [objDAO deleteDireccionCliente:intIdUsuario];
        
        int intIdDireccionClienteiPad = [ [[json objectAtIndex:0] objectForKey:@"iddir"] intValue];
        
        if (intIdDireccionClienteiPad != 0) {
            
            int intIdComuna = [ [[json objectAtIndex:0] objectForKey:@"idcom"] intValue];
            
            NSString *strStreet = [[json objectAtIndex:0] objectForKey:@"dir"];
            
            NSString *strNumberStreet = [[json objectAtIndex:0] objectForKey:@"numd"];
            
            NSString *strReference = [[json objectAtIndex:0] objectForKey:@"ref"];
            
            intRetorno = [objDAO insertDireccionCliente:intIdUsuario intIdDireccion:intIdDireccionClienteiPad intRutCliente:intRutCliente strDireccion:strStreet strNumero:strNumberStreet strReferencia:strReference intIdComuna: intIdComuna];
            
            if (intRetorno <= 0) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"Error al actualizar la dirección del cliente, intente nuevamente."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
                
                return NO;
                
            }else{
                
                return YES;
            }
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"Debe especificar su direción de despacho en el sistema."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return YES; //Por ahora si esta creado el usuario en el portal, pero no especificó dirección lo obligamos a completarla.
        }
        
    }else{
        return NO;
    }
    
}

- (bool) clientInfoCloud:(int) intIdUsuario {
    
    dao *objDAO = [[dao alloc] init];
    
    bool blnRetorno = YES;
    int intRetorno = 0;
    int intRutCliente = 0;
    int intDia = 0;
    int intMes = 0;
    int intAno = 0;
    int intFormaPago = 1;
    
    NSString *strDigito = @"";
    NSString *strNombreCompleto = @"";
    NSString *strApellidos = @"";
    NSString *strTelefono = @"";
    NSString *strSex = @"";
    NSString *strFechaNacimiento = @"";
    NSString *strEmail = @"";
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonDatosCliente&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        //[{"idcli":"28", "tpcli":"1", "rut":"12814052", "dig":"2", "nom":"Yessica Andrea", "ape":"Arias Sudy", "rz":"", "nomf":"", "tel":"", "fnan":"19752323", "sex":"F", "rub":"", "cel":"56276800", "mail":"yessica.arias.sudy@gmail.com" }]
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        intRutCliente = [ [[json objectAtIndex:0] objectForKey:@"rut"] intValue];
        strDigito = [[json objectAtIndex:0] objectForKey:@"dig"];
        strDigito = [[json objectAtIndex:0] objectForKey:@"dig"];
        strNombreCompleto = [[json objectAtIndex:0] objectForKey:@"nom"];
        strApellidos = [[json objectAtIndex:0] objectForKey:@"ape"];
        strTelefono = [[json objectAtIndex:0] objectForKey:@"cel"];
        strFechaNacimiento = [[json objectAtIndex:0] objectForKey:@"fnan"];
        strEmail = [[json objectAtIndex:0] objectForKey:@"email"];
        
        if (  (![strFechaNacimiento  isEqual: @"0"]) && (![strFechaNacimiento  isEqual: @""])  ) {
            
            intDia = [[strFechaNacimiento substringWithRange:NSMakeRange(strFechaNacimiento.length-2, 2 )] intValue];
            intMes = [[strFechaNacimiento substringWithRange:NSMakeRange(strFechaNacimiento.length-4, 2 )] intValue];
            intAno = [[strFechaNacimiento substringWithRange:NSMakeRange(0, 4)] intValue];
            
        }else{
            intDia = 0;
            intMes = 0;
            intAno = 0;
        }
        
        strSex = [[json objectAtIndex:0] objectForKey:@"sex"];
        
        if ([objDAO obtainMaestroClientes: intIdUsuario] > 0) {
            //Actualizamos
            
            intRetorno = [objDAO upateMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
            
            if (intRetorno > 0) {
                
                blnRetorno = YES;
            } else {
                blnRetorno = NO;
            }
            
        }else{
            //Insertamos
            intRetorno = [objDAO insertMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
            
            if (intRetorno > 0) {
                
                blnRetorno = YES;
            } else {
                blnRetorno = NO;
            }
        }
        
        if (blnRetorno) {
            
            blnRetorno = [self clientDirectionInfoCloud:intIdUsuario intRutCliente:intRutCliente];
        }
        
    }else{
        blnRetorno = NO;
    }
    
    return blnRetorno;
}

- (void)viewWillAppear:(BOOL)animated {
    
    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteRegisterBack];
    
    viewSavingClientInfo.hidden = NO;
    
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    bool blnRetorno = YES;
    
    blnRetorno = [self clientInfoCloud:intIdUsuario];
    
    if (blnRetorno) {

        viewSavingClientInfo.hidden = YES;
//      btnNext.hidden = NO;
        btnEdit.hidden = NO;
        
        [self retrieveClient];
        
    }else{
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Error remoto al intentar obtener la información del cliente, intente nuevamente."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)backToCart:(id)sender {
    
    //  [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    
    //  [self.navigationController popToRootViewControllerAnimated:YES];
    
    /*
     dao *objDAO = [[dao alloc] init];
     
     //0 = Home App
     //1 = Register
     //2 = Edición del despacho
     
     if ([objDAO obtainRegisterBack] == 0) {
     
     //Back desde el home
     
     UIViewController *rvController = [self.storyboard instantiateViewControllerWithIdentifier:@"registerHome"];
     [self.navigationController popViewControllerAnimated:rvController];
     
     //[self.navigationController popToRootViewControllerAnimated:YES];
     //[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
     }else{
     
     UIViewController *rvController = [self.storyboard instantiateViewControllerWithIdentifier:@"registerHome"];
     
     [self.navigationController popViewControllerAnimated:rvController];
     
     }
     */
    
    
}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (IBAction)gotoRegister:(id)sender {
    
    dao *objDAO = [[dao alloc] init];
    
    //0 = Home App
    //1 = Register
    //2 = Edición del despacho
    
    [objDAO deleteRegisterBack];
    [objDAO insertRegisterBack:2];
    
    [self performSegueWithIdentifier:@"segueRegister" sender:nil];
    
}

@end